// Copyright (c) 2023 坚果派
// 公众号：nutpi
// 电话：17752170152
// 官网：https://www.nutpi.net/
// All rights reserved.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/weight_management_provider.dart';
import '../utils/bmi_calculator.dart';
import '../providers/page_navigation_provider.dart';
import 'package:intl/intl.dart';

class WeightDashboardWidget extends StatelessWidget {
  const WeightDashboardWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<WeightManagementProvider>(
      builder: (context, provider, child) {
        final latestRecord = provider.latestRecord;

        if (latestRecord == null) {
          return _buildEmptyState(context);
        }

        // Check for valid DateTime to prevent DateFormat errors
        String formattedDate;
        try {
          formattedDate =
              DateFormat('MM/dd HH:mm').format(latestRecord.recordTime);
        } catch (e) {
          formattedDate = '未知时间';
        }

        return Card(
          elevation: 2,
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '体重管理',
                      style: Theme.of(context).textTheme.titleLarge?.copyWith(
                            fontWeight: FontWeight.bold,
                          ),
                    ),
                    Text(
                      '更新于: $formattedDate',
                      style: TextStyle(color: Colors.grey[600], fontSize: 12),
                    ),
                  ],
                ),
                const Divider(),
                const SizedBox(height: 8),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildWeightInfo(
                      context,
                      '${latestRecord.weight} kg',
                      '当前体重',
                      Icons.monitor_weight,
                    ),
                    if (latestRecord.bmi != null)
                      _buildWeightInfo(
                        context,
                        latestRecord.bmi!.toStringAsFixed(1),
                        'BMI指数',
                        Icons.speed,
                        _getBmiColor(latestRecord.bmi!),
                      ),
                    if (latestRecord.waistCircumference != null)
                      _buildWeightInfo(
                        context,
                        '${latestRecord.waistCircumference} cm',
                        '腰围',
                        Icons.straighten,
                      ),
                  ],
                ),
                const SizedBox(height: 16),
                if (latestRecord.bmi != null)
                  _buildBmiStatusBox(context, latestRecord.bmi!),
                const SizedBox(height: 8),
                if (provider.weightRecords.length >= 2)
                  Padding(
                    padding: const EdgeInsets.only(top: 8.0),
                    child: Row(
                      children: [
                        Icon(
                          provider.weightChangeTrend > 0
                              ? Icons.trending_up
                              : provider.weightChangeTrend < 0
                                  ? Icons.trending_down
                                  : Icons.trending_flat,
                          color: provider.weightChangeTrend > 0
                              ? Colors.red
                              : provider.weightChangeTrend < 0
                                  ? Colors.green
                                  : Colors.blue,
                        ),
                        const SizedBox(width: 8),
                        Expanded(
                          child: Text(
                            provider.weightChangeTrend > 0
                                ? '上次记录以来体重增加了 ${provider.weightChangeTrend.abs().toStringAsFixed(1)} kg'
                                : provider.weightChangeTrend < 0
                                    ? '上次记录以来体重减少了 ${provider.weightChangeTrend.abs().toStringAsFixed(1)} kg'
                                    : '体重没有变化',
                          ),
                        ),
                      ],
                    ),
                  ),
                const SizedBox(height: 16),
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: () {
                      Provider.of<PageNavigationProvider>(context,
                              listen: false)
                          .changePage(2); // Index of weight management page
                    },
                    child: const Text('查看详细记录'),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildBmiStatusBox(BuildContext context, double bmi) {
    Color statusColor;
    String statusText;

    try {
      statusColor = BMICalculator.getBMIColor(bmi);
      statusText = BMICalculator.getBMICategory(bmi);
    } catch (e) {
      statusColor = Colors.grey;
      statusText = "未知";
    }

    return Container(
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: statusColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Icon(Icons.info_outline, color: statusColor),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              '您的体重状态: $statusText',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                color: statusColor,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Color _getBmiColor(double bmi) {
    try {
      return BMICalculator.getBMIColor(bmi);
    } catch (e) {
      return Colors.grey;
    }
  }

  Widget _buildWeightInfo(
      BuildContext context, String value, String label, IconData icon,
      [Color? color]) {
    return Column(
      children: [
        Icon(icon, size: 24, color: color ?? Theme.of(context).primaryColor),
        const SizedBox(height: 8),
        Text(value,
            style: TextStyle(
                fontWeight: FontWeight.bold, fontSize: 16, color: color)),
        Text(label, style: TextStyle(color: Colors.grey[600], fontSize: 12)),
      ],
    );
  }

  Widget _buildEmptyState(BuildContext context) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Icon(Icons.scale, size: 64, color: Colors.grey[400]),
            const SizedBox(height: 16),
            const Text('暂无体重记录',
                style: TextStyle(fontSize: 18, color: Colors.grey)),
            const SizedBox(height: 8),
            Text('开始记录您的体重变化吧！',
                style: TextStyle(fontSize: 14, color: Colors.grey[600])),
            const SizedBox(height: 24),
            ElevatedButton.icon(
              icon: const Icon(Icons.add),
              label: const Text('添加记录'),
              onPressed: () {
                try {
                  Provider.of<PageNavigationProvider>(context, listen: false)
                      .changePage(2);
                } catch (e) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('导航失败: $e')),
                  );
                }
              },
            ),
          ],
        ),
      ),
    );
  }
}
